<template>
  <div>
    <q-file
      ref="myUploadRef"
      v-model="myImgRef"
      label="Pick one file"
      outlined
      clearable
      color="teal"
      :max-files="1"
      accept=".jpg, .jpeg, .png, .bmp, .gif"
      style="max-width: 300px"
      @update:model-value="uploadFile"
      @clear="clearImage"
    >
      <template v-slot:append>
        <q-btn round dense flat icon="cloud_upload" @click="postFile"/>
      </template>
    </q-file>
  </div>
  <div>
    <q-img
      :src="imgURL"
      spinner-color="white"
      style="height: 140px; max-width: 150px"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, toRefs, ref, onMounted } from 'vue';
import api from 'axios';


export default defineComponent({
  name: 'AmyUploaderBtn',
  props: {
    uploaderUrl: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  setup (props, context) {
    let myImgRef = ref<File | null>(null);
    let imgURL = ref('');
    let myUploadRef = ref(null);

    const clearImage = () => {
      imgURL.value = '';
    }

    const uploadFile = () => {
      console.log('handleUpload is triggered');
      if (myImgRef.value) {
        imgURL.value = URL.createObjectURL(myImgRef.value);
      }
    }

    const postFile = () => {
      if (myImgRef.value) {
        const url = 'api/upload/image/logo'
        const fileData = new FormData()
        fileData.append('logo', myImgRef.value)
        api.post(url, fileData, {
          headers: {
            'Content-Type': 'multipart/form-com_data'
          }
        }).then((response) => {
          console.log('SUCCESS!!');
        }).catch(() => {
          console.log('FAILURE!!')
        })
      }
    }

    return {
      myImgRef,
      imgURL,
      myUploadRef,
      clearImage,
      uploadFile,
      postFile
    };
  }
})
</script>

<style scoped>

</style>
